import { uplodaImage } from "./../api/common";
import { Dispatch, SetStateAction, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { message } from "antd";

export const useLocalStorage = <T = string>(key: string) => {
	const [value, setValue] = useState<T | null>(null);
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	const handleSet = (outerValue: any) => {
		setValue(outerValue);
		if (outerValue) {
			localStorage.setItem(key, JSON.stringify(outerValue));
		}
	};
	const handleRemove = () => {
		localStorage.removeItem(key);
	};
	useEffect(() => {
		const storedValue = localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : null;
		setValue(storedValue);
		//eslint-disable-next-line
	}, []);
	return [value, handleSet, handleRemove] as [T | null, Dispatch<SetStateAction<T | null>>, () => null];
};

export const useWatch = (cb: () => void, dependences: unknown[]) => {
	const invoked = useRef(false);
	useEffect(() => {
		if (invoked.current) {
			cb();
		}
		invoked.current = true;
		//eslint-disable-next-line
	}, dependences);
};

export const useLayoutWatch = (cb: () => void, dependences: unknown[]) => {
	const invoked = useRef(false);
	useLayoutEffect(() => {
		if (invoked.current) {
			cb();
		}
		invoked.current = true;
		//eslint-disable-next-line
	}, dependences);
};

export const useMount = (cb: () => void) => {
	useEffect(() => {
		cb();
	}, []);
};

export const useUploadImage = (cb?: (path: string) => void) => {
	const input = useMemo(() => {
		const i = document.createElement("input");
		i.type = "file";
		i.accept = "image/jpeg,image/png,image/webp";
		return i;
	}, []);
	const uploadCb = useRef<(path?: string) => void>();
	input.onchange = async () => {
		const file = input.files?.[0];
		if (!file) return;
		const isLt5M = file.size / 1024 / 1024 < 5;
		if (!isLt5M) {
			message.error("图片大小必须小于5MB!");
		}
		const formData = new FormData();
		formData.append("file", file);
		const { data } = await uplodaImage(formData);
		// cb?.(`${process.env.REACT_APP_BASEURL}${data}`);
		cb?.(data);
		// uploadCb.current?.(`${process.env.REACT_APP_BASEURL}${data}`);
		uploadCb.current?.(data);
	};
	return {
		upload(cb?: (path?: string) => void) {
			input.value = "";
			input.click();
			cb && (uploadCb.current = cb);
		},
	};
};
